import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list:[],
    inputValue:'aaa',
    nextId:5,
    view:'all',
    
  },
  getters: {
    unDone(state){
      return state.list.filter(x=>x.done===false).length
    },
    


    infoList(state){
      if(state.view==='all'){
        return state.list
      }
      if(state.view==='undone'){
        return state.list.filter(x=>!x.done)
      }
      if(state.view==='done'){
        return state.list.filter(x=>x.done)
      }
    }
  },
  mutations: {

    initList(state,listArr){
      state.list=listArr
    },
    // 为store中的inputValue赋值
    setInput(state,val){
      state.inputValue=val
    },
    addItem(state){
 
      const obj={
        id:state.nextId,
        info:state.inputValue.trim(),
        done:false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue=''
   

    },
    // 根据ID删除对应的任务事项
    removeItemId(state,id){
      const i=state.list.findIndex(x=>x.id===id)
      // 根据索引，删除对应的元素
      if(i !==-1){ //索引存在
        state.list.splice(i,1)
      }
    },
    changeItem(state,param){
      const i= state.list.findIndex(x=>x.id===param.id)
      if(i!==-1){
        state.list[i].done=param.status
      }
    },
    cleanDone(state){
      state.list=state.list.filter(x=>x.done===false)
    },
    viewKey(state,key){
      state.view=key
    }
  },
  actions: {
    
    getList(context){
      axios.get('/list.json').then(({data})=>{
        console.log(data)
        context.commit('initList',data)
      })
    }
  },
  modules: {
  }
})
